package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.data.Result;
import com.dongdongshop.em.ConstantEnum;
import com.dongdongshop.pojo.TbSeller;
import com.dongdongshop.service.TbSellerService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("seller")
public class SellerController {

    @Reference
    private TbSellerService tbSellerService;

    @RequestMapping("register")
    public String register(){
        return "/register";
    }

    @RequestMapping("getIndex")
    public String getIndex(){
        return "admin/index";
    }


    @RequestMapping("getRegisterInfo")
    @ResponseBody
    public Result getRegisterInfo(TbSeller tbSeller){
        String s = ShiroUtils.generateSalt(6);
        String md5 = ShiroUtils.encryptPassword("MD5", tbSeller.getPassword(), s, 3);
        tbSeller.setSalt(s);
        tbSeller.setPassword(md5);
            tbSellerService.getRegisterInfo(tbSeller);
        return Result.build(ConstantEnum.REGISTER_SUCCESS);
    }

    @RequestMapping("getLoginInfo")
    @ResponseBody
    public Result getLoginInfo(String sellerId, String password, Model model){
        // 使用 shiro 的登录功能
        // 1. 需要获取 subject 对象
        Subject subject = SecurityUtils.getSubject();
        // 2. 将账号 密码封装成 token 对象
        UsernamePasswordToken token = new UsernamePasswordToken(sellerId,password);
        // 3. 调用subject的login方法执行登录逻辑
        // 我们方法调用的时候,被调用的方法如何如何告诉我们 执行的功能是否成功
        // 1.返回值(最常用)  2.通过抛异常的方式
        // shiro 使用的就是抛异常的方式
        try {
            subject.login(token);
        }catch (UnknownAccountException e){
            model.addAttribute("message","账号未注册在");
            System.out.println("账号不存在");
            return Result.build(ConstantEnum.REGISTER_ERROR);
        }catch (IncorrectCredentialsException e){
            model.addAttribute("message","密码错误");
            System.out.println("密码错误");
            return Result.build(ConstantEnum.PWD_ERROR);
        }catch (LoginException loginException){
            model.addAttribute("message","账号待审核");
            System.out.println("账号待审核");
            return Result.build(ConstantEnum.REGISTER_SUCCESS);
        }
        return Result.build(ConstantEnum.LOGIN_SUCCESS);
    }

}
